using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
using DG.Tweening;

public class SlingShotHandler : MonoBehaviour
{
    [Header("Line Renderers")]
    [SerializeField] private LineRenderer leftLineRenderer;
    [SerializeField] private LineRenderer rightLineRenderer;
    [Header("Transform References")]
    [SerializeField] private Transform leftStartPosition;
    [SerializeField] private Transform rightStartPosition;
    [SerializeField] private Transform elasticTransform;
    [SerializeField] private Transform centerPosition;
    [SerializeField] private Transform lidePosition;
    [Header("Slingshot Stats")]
    [SerializeField] private float maxDistance = 3f;
    [SerializeField] private float timeBetweenBirdRespawns;
    [SerializeField] private float elasticDivider = 1.2f;
    [SerializeField] private AnimationCurve elasticCurve;
    [Header("SlingShotAera Scripts")]
    [SerializeField] private SlingShotAera slingShotAera;
    [Header("Angie Bird")]
    [SerializeField] private AngieBird angieBirdPrefab;
    [SerializeField] private float angieBirdPositionOffset;
    [SerializeField] private float launchForce;
    private Vector2 slingShotLinesPosition;
    private Vector2 direction;
    private Vector2 directionNormalized;
    private bool clickWithinAera;
    private bool birdOnSlingShot;
    private AngieBird angieBird;
    // 隐藏线条
    private void Awake()
    {
        leftLineRenderer.enabled = false;
        rightLineRenderer.enabled = false;
        SpawnAngieBird();
    }

    private void Update()
    {
        if (Mouse.current.leftButton.wasPressedThisFrame && slingShotAera.IsWithinSlingshotAera()) clickWithinAera = true;

        if (Mouse.current.leftButton.IsPressed() && clickWithinAera && birdOnSlingShot)
        {
            DrawSlingShot();
            BirdsPositionAndRotation();
        }

        if (Mouse.current.leftButton.wasReleasedThisFrame && clickWithinAera && birdOnSlingShot)
        {
            LaunchOneBird();
        }
    }

    private void LaunchOneBird()
    {
        if (GameManager.instance.HasEnoughShots())
        {
            birdOnSlingShot = false;
            clickWithinAera = false;

            angieBird.LaunchBird(direction, launchForce);
            AnimateSlingShot();

            GameManager.instance.UseShot();

            if (GameManager.instance.HasEnoughShots()) StartCoroutine(SpwanAngieBirdAfterTime());
        }
    }
    // 画线条方法
    private void DrawSlingShot()
    {
        // 鼠标坐标转换成世界坐标
        Vector3 touchPosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        // 限制线条位置的最大长度
        slingShotLinesPosition = centerPosition.position + Vector3.ClampMagnitude(touchPosition - centerPosition.position, maxDistance);

        SetLines(slingShotLinesPosition);
        // 计算从 slingShotLinesPosition 指向 centerPosition 的向量
        direction = (Vector2)centerPosition.position - slingShotLinesPosition;
        directionNormalized = direction.normalized;
    }

    private void SetLines(Vector3 position)
    {
        // 显示线条
        if (!leftLineRenderer.enabled && !rightLineRenderer.enabled)
        {
            leftLineRenderer.enabled = true;
            rightLineRenderer.enabled = true;
        }

        // 绘制两个线条头尾的位置
        leftLineRenderer.SetPosition(0, position);
        leftLineRenderer.SetPosition(1, leftStartPosition.position);

        rightLineRenderer.SetPosition(0, position);
        rightLineRenderer.SetPosition(1, rightStartPosition.position);
    }

    private void SpawnAngieBird()
    {
        SetLines(lidePosition.position);

        // 计算从 lidePosition 指向 centerPosition 的归一化方向
        Vector2 dir = (centerPosition.position - lidePosition.position).normalized;
        // 生成点位置等于闲置位置加上指向中心点的朝向加上偏移量
        Vector2 spawnPosition = (Vector2)lidePosition.position + dir * angieBirdPositionOffset;

        angieBird = Instantiate(angieBirdPrefab, spawnPosition, Quaternion.identity);
        // 生成时让鸟面向弹弓中间
        angieBird.transform.right = dir;

        birdOnSlingShot = true;
    }

    private void BirdsPositionAndRotation()
    {
        // 小鸟位置等于弹弓线的位置加上往中心点朝向向量加上偏移量
        // 使小鸟在各个角度发射时都朝向弹弓中心点
        angieBird.transform.position = slingShotLinesPosition + directionNormalized * angieBirdPositionOffset;
        // 让鸟的面始终朝向弹弓中间
        angieBird.transform.right = directionNormalized;
    }

    private IEnumerator SpwanAngieBirdAfterTime()
    {
        yield return new WaitForSeconds(timeBetweenBirdRespawns);
        SpawnAngieBird();
    }

    #region Animate SlingShot 弹弓动画
    private void AnimateSlingShot()
    {
        // 设置橡皮筋动画位置从拖拽位置开始
        elasticTransform.position = leftLineRenderer.GetPosition(0);
        // 计算拖拽位置距离中心点的位置
        float dist = Vector2.Distance(elasticTransform.position, centerPosition.position);
        // 动画持续时间 拉伸越长动画时间越长
        float time = dist / elasticDivider;
        // 使用动DG插件 从elastic点移动到center点 持续time时间
        elasticTransform.DOMove(centerPosition.position, time).SetEase(elasticCurve);
        // 启用协程更新线的位置
        StartCoroutine(AnimateSlingShotLines(elasticTransform, time));
    }

    private IEnumerator AnimateSlingShotLines(Transform transform, float time)
    {
        float elasticTime = 0f;
        while (elasticTime < time)
        {
            // 动画持续时间time之内
            elasticTime += Time.deltaTime;
            // 每帧渲染新的位置
            // 由于transform是引用类型，这里的transform指向的是它的内存地址
            // 外部的DOMove在持续修改elastic的位置
            SetLines(transform.position);

            yield return null;
        }
    }
    #endregion
}
